package com.pjedu.nbmalladminsystem.web;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.pjedu.nbmallcommon.common.ServiceResultEnum;
import com.pjedu.nbmallcommon.utils.MD5Util;
import com.pjedu.nbmallcommon.utils.Result;
import com.pjedu.nbmallcommon.utils.ResultGenerator;
import com.pjedu.nbmalluser.entity.MallAdminUser;
import com.pjedu.nbmalluser.service.MallAdminUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Author 汪洋
 * @Description
 */
@RestController
@RequestMapping("admin")
@Api(tags = "处理Admin的相关Controller")
public class AdminController {
    @Resource
    private MallAdminUserService myAdminUserService;
    @Resource
    private DefaultKaptcha captchaProducer;
    @ApiOperation(value = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="loginUserName",value = "用户名",required = true),
            @ApiImplicitParam(name="loginPassword",value = "密码",required = true),
            @ApiImplicitParam(name="verifyCode",value = "验证码",required = true),
    })
    @PostMapping("login")
    public Result login(@RequestParam("loginUserName") String username,
                        @RequestParam("loginPassword") String password,
                        @RequestParam("verifyCode") String verifyCode,
                        HttpSession session){
        //1、非空判断
        if (!StringUtils.hasText(username)||!StringUtils.hasText(password)||!StringUtils.hasText(verifyCode)){
            return ResultGenerator.genFailResult("数据为空");
        }
        //2、模拟数据进行登录
        /*if ("admin".equals(username)&&"admin".equals(password)){
            return ResultGenerator.genSuccessResult();
        }else{
            return ResultGenerator.genFailResult("用户名密码不正确");
        }*/
        //4、加入验证码的校验
        if (!session.getAttribute("loginVerifyCode").equals(verifyCode)){
            return ResultGenerator.genFailResult("验证码不正确");
        }
        //3、进行登录的service方法调用
        MallAdminUser user = MallAdminUser.builder().
                loginUserName(username).
                loginPassword(MD5Util.MD5Encode(password, "UTF-8")).
                build();
        MallAdminUser loginUser = myAdminUserService.login(user);
        //3.1、如果登录成功
        if (loginUser != null) {
            //3.2、把登录的对象存储到session中进行状态管理
            session.setAttribute("adminUser",loginUser);
            //3.3、返回一个登陆成功的result对象
            return ResultGenerator.genSuccessResult();
        //3.2、如果登录失败
        }else{
            return ResultGenerator.genFailResult("用户名密码不正确");
        }
    }
    @GetMapping("login/kaptcha")
    public void getKaptcha(HttpSession httpSession, HttpServletResponse httpServletResponse) throws IOException {
        // 1. 生成验证文字内容
        String verifyCode = captchaProducer.createText();
        // 1.1 把验证码的内容放到session里面【服务器存储】
        httpSession.setAttribute("loginVerifyCode", verifyCode);
        // 1.2 把验证码生成的文字内容构建成一张图片
        BufferedImage image = captchaProducer.createImage(verifyCode);
        // 2. 返回图片内容到页面
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", imgOutputStream);
        byte[] byteImage = imgOutputStream.toByteArray();
        // 2.1 返回的响应内容中就是图片， 同时设置 响应头， 浏览器根据类型去识别
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        httpServletResponse.getOutputStream().write(byteImage);
        httpServletResponse.getOutputStream().flush();
        httpServletResponse.getOutputStream().close();
        System.out.println("获取一个验证码");
    }

    @PostMapping("/profile/password")
    public String passwordUpdate(HttpSession session, @RequestParam("originalPassword") String originalPassword,
                                 @RequestParam("newPassword") String newPassword) {
        if (StringUtils.isEmpty(originalPassword) || StringUtils.isEmpty(newPassword)) {
            return "参数不能为空";
        }
        Integer loginUserId = ((MallAdminUser) session.getAttribute("adminUser")).getAdminUserId();
        if (myAdminUserService.updatePassword(loginUserId, originalPassword, newPassword)) {
            //修改成功后清空session中的数据，前端控制跳转至登录页
            session.removeAttribute("loginUser");
            session.removeAttribute("errorMsg");
            return ServiceResultEnum.SUCCESS.getResult();
        } else {
            return "修改失败";
        }
    }

    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public Result logout(HttpSession session) {
        session.removeAttribute("adminUser");
        return ResultGenerator.genSuccessResult();
    }

}
